package java.utils;

/**
 * @Author Su
 * @Date 2025/4/17 16:14
 * @Version 1.0 （版本号）
 */
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class CaptchaUtil {
    // 验证码字符集
    private static final char[] CAPTCHA_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".toCharArray();
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    private static final int INTERFERENCE_LINES = 20;

    // 生成验证码图片和文本
    public static Captcha generateCaptcha() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 生成随机验证码
        StringBuilder captchaText = new StringBuilder();
        Random random = new Random();

        // 绘制字符
        g.setFont(new Font("Arial", Font.BOLD, 25));
        for (int i = 0; i < CODE_LENGTH; i++) {
            char c = CAPTCHA_CHARS[random.nextInt(CAPTCHA_CHARS.length)];
            captchaText.append(c);

            // 随机颜色
            g.setColor(new Color(
                    random.nextInt(150),
                    random.nextInt(150),
                    random.nextInt(150)));

            // 绘制字符（带随机偏移）
            g.drawString(String.valueOf(c), 20 * i + 10, 25 + random.nextInt(10));
        }

        // 添加干扰线
        g.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < INTERFERENCE_LINES; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            return new Captcha(captchaText.toString(), baos.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("生成验证码失败", e);
        }
    }

    public static class Captcha {
        private final String text;
        private final byte[] imageData;

        public Captcha(String text, byte[] imageData) {
            this.text = text;
            this.imageData = imageData;
        }

        public String getText() {
            return text;
        }

        public byte[] getImageData() {
            return imageData;
        }
    }
}